package com.awspaass.user.apps.syncwechataddress;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CheckData {
	public static String readToString(String fileName) {
		String encoding = "UTF-8";
		File file = new File(fileName);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) throws Exception {

		System.out.println("##########################Test!");
		String cfgstr = readToString("C:\\test\\company.json");
		long timeFlag = new Date().getTime();
		JSONArray companyArray = null;
		JSONObject jsonObject = JSON.parseObject(cfgstr);
		if (jsonObject != null) {
			// 取出按钮权限的数据
			companyArray = jsonObject.getJSONArray("companys");
		}
		Iterator<Object> num = companyArray.iterator();
		while (num.hasNext()) {
			JSONObject company = (JSONObject) num.next();
			String c_wechatid = (String) company.get("companywechatid");
			String c_secret = (String) company.get("companywechatseret");
			String c_awsid = (String) company.get("awsid");
			String role = (String) company.get("companyuserrole");
			String cksecret = (String) company.get("ckseret");
			int totalCkNumber=0;
			if (!cksecret.equals("")) {
				WeChatUtil wechat = new WeChatUtil();

				String access_token = wechat.getAccessToken(c_wechatid, c_secret);

				List<Map<String, String>> depsWechat = wechat.getDepartmentList(access_token);

				List<WxUserInfo> wechatuserlist = wechat.getDepartmentUserDetails(depsWechat, access_token, "0");
				int page=wechatuserlist.size()/100+1;
				for(int i =0;i<page;i++) {
					List t= new ArrayList();
					int max=0;
					if(i+1==page) {
						max=wechatuserlist.size()%100;
					}else {
						max=100;
					}
					for(int j=0; j<max;j++) {
						int index = i*100+j;
						WxUserInfo w=wechatuserlist.get(index);
						String id = w.getUserId();
						t.add(id);
					}
					totalCkNumber+=getDKData(c_wechatid, cksecret, t);
					
				}
				System.out.println(totalCkNumber);
			}

		}

	}

	public static String getDKToken(String corpid, String cksecret) {
		String ss = null;
		try {
			// 当前时间戳
			String generalUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"; // Token地址
			URL url = new URL(generalUrl);
			String strRead = null;
			StringBuffer sbf = new StringBuffer();
			// 连接接口路径
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			// 设置请求属性
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setUseCaches(false);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// 建立连接
			connection.connect();
			OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
			// 插入Body里面的json数据
			JSONObject parm = new JSONObject();
			parm.put("corpid", corpid); // AppKey
			parm.put("corpsecret", cksecret);// AppSecre
			writer.write(parm.toString());
			writer.flush();
			InputStream is = connection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close(); // 关流
			connection.disconnect();
			ss = JSON.parseObject(sbf.toString()).getString("access_token"); // 获取data对象
			if ("".equals(ss) || ss == null) {
				System.out.println("获取token失败>>>>>ss的值是：" + ss);
			}
			// 返回token字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		//System.out.println(ss);
		return ss;
	}

	public static int getDKData(String corpid, String cksecret, List userlist) throws Exception {

		long kssj = 1647187200; // 开始时间
		long jssj = 1647230400; // 结束时间
		String generalUrl = " https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token="
				+ getDKToken(corpid, cksecret) + ""; // Token地址
		URL url = new URL(generalUrl);
		String strRead = null;
		StringBuffer sbf = new StringBuffer();
		// 连接接口路径
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		// 设置请求属性
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
		// 建立连接
		connection.connect();
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
		// 插入Body里面的json数据
		JSONObject parm = new JSONObject();
		parm.put("opencheckindatatype", "3"); // AppKey
		parm.put("starttime", kssj); // AppKey
		parm.put("endtime", jssj);// AppSecre
		//System.out.println(userlist);
		parm.put("useridlist", userlist);// AppSecre
		writer.write(parm.toString());
		writer.flush();
		InputStream is = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		while ((strRead = reader.readLine()) != null) {
			sbf.append(strRead);
			sbf.append("\r\n");
		}
		reader.close(); // 关流
		connection.disconnect();
		JSONArray j = JSON.parseObject(sbf.toString()).getJSONArray("checkindata");
		//System.out.println(j.size());
		//System.out.println(sbf.toString());
		//return JSONObject.parseObject(sbf.toString());// .getString("checkindata");
		return j.size();
	}

}
